#if 1
#define _XOPEN_SOURCE  1
#define _XOPEN_SOURCE_EXTENDED 1
#define _BSD_SOURCE  1
#define _SVID_SOURCE  1
#define _POSIX_SOURCE  1
#endif
#include <header.h>
#include "Connection.h"
#include "Queue.h"
#include "PublicUtils.h"
#include "mysql.h"
#include "ThreadPool.h"
#include "HashMap.h"
#include "Global.h"
#include "HashSet.h"
#include "CircularQueue.h"


void closeAllInSet(int net_fd){
	printf("超时踢出客户端 netfd = %d\n", net_fd);
	close(net_fd);
}


void closeTheCurrentSlot(int sig){
	curr = (curr + 1) % slotQueue->capacity;
	// printf("%d秒过去了\n", curr);
	/* 需要加锁 */
	
	/* close()并清空当前集合 */	
	if(slotQueue->data[curr]->size > 0){		
		hashset_iterate(slotQueue->data[curr], closeAllInSet);
		hashset_clear(slotQueue->data[curr]);
	}

}

int main(int argc, char* argv[]){
	/* 启动线程池 */
	pool_t pool;
	initPool(&pool, 3);

	/* 监听socket */
	int socket_fd;
	SocketDriver(&socket_fd);
	
	/* epoll监听socket */
	int epoll_fd = epoll_create(1);
	addEpoll(epoll_fd, socket_fd);
	
	/* 初始化slot队列 */
	map = create_hashmap(1000);
	slotQueue = create_queue(sizeof(HashSet));
	initSlotQueue(slotQueue);

	/* 注册定时器 */
    signal(SIGALRM, closeTheCurrentSlot);
	initTimer();

	while(1){
		struct epoll_event list[5];
		int epoll_num = epoll_wait(epoll_fd, list, 5, -1);

		for (int i = 0; i < epoll_num; i++){
			if(list[i].data.fd == socket_fd){
				/* 有新客户端到来 */
				int net_fd = accept(socket_fd, NULL, NULL);

                /* 将新连接加入任务队列，并唤醒工作线程处理 */
				pthread_mutex_lock(&pool.lock);
				enQueue(&pool.queue, net_fd);
				pthread_cond_broadcast(&pool.cond);
				pthread_mutex_unlock(&pool.lock);
			}
		}		
	}

	slotQueue->destroy(slotQueue);
	destroy_hashmap(map);
	close(socket_fd);
	return 0;
}
